//
//  AuthenicateImageViewController.m
//  QRMaster
//
//  Created by myApple on 16/4/11.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "AuthenicateImageViewController.h"
#import "AFNetworking.h"
#import "PromptInfoView.h"
#import "AuthenicateInfoHeadView.h"
#import "UIImageView+WebCache.h"
#import "ShowLargeImageController.h"
#import "validateInputValue.h"
#import "IQKeyboardManager.h"

@interface AuthenicateImageViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate>
{
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UITableView * imageTabelView;
    NSArray * headTitelArray;
    UIImageView * minImageView;
    UITextField * certificateTextField;
    NSString * certificateString;
    NSString * minImageUrl;
    UIImage * newImage;//新的image
    NSString * largeImageUrl;
    BOOL imageChangeFlag;//图片是否改变
    UIActionSheet * noImageSheetView;
    UIActionSheet * hasImageSheetView;
}

@end

@implementation AuthenicateImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"authenImage", @"证件信息");
    imageChangeFlag = NO;
    [self prepareView];
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(submit)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit", @"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
}

-(void)prepareView
{
    imageTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    imageTabelView.delegate = self;
    imageTabelView.dataSource = self;
    imageTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:imageTabelView];
}

#pragma mark ----------- 提交保存
-(void)submit
{
    [[IQKeyboardManager sharedManager] resignFirstResponder];
    if (_infoModel.status == 2 || _infoModel.status == 3) {
       UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"feedBackAlterPromt", @"提示") message:NSLocalizedString(@"modifyAuthenPromt", @"改物业认证资料将重新审核，审核期间锁掌柜不可用")  delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消") otherButtonTitles:NSLocalizedString(@"alterSure",@"确认"), nil];
        [alertView show];
    }
    else
    {
        NSData *imageData = UIImageJPEGRepresentation(newImage, 0.0001);
        [self postImage:imageData];
    }
   
}

#pragma mark -------- UIAlertViewDelegate、
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSData *imageData = UIImageJPEGRepresentation(newImage, 0.0001);
        [self postImage:imageData];
    }
}

-(void)setInfoModel:(AuthenBaseInfoModel *)infoModel
{
    _infoModel = infoModel;
    minImageUrl = infoModel.thumbnail;
    largeImageUrl = infoModel.image;
    certificateString = infoModel.no;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        return 44;
    }
    else
    {
        return 150;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 5.0;
    }
    else
    return 33;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        AuthenicateInfoHeadView * headView = [[AuthenicateInfoHeadView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 33)];
        headView.titleName = NSLocalizedString(@"certificateNo", @"证件号码");
        return headView;
    }
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellId = @"cellId";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    if (indexPath.section == 0) {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(16, 20, 100, 17)];
        label.text = NSLocalizedString(@"certificateImage", @"证件图片");
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = UIColorFromRGBAndA(0x333333, 0.6);
        [cell addSubview:label];
        
        minImageView = [[UIImageView alloc]initWithFrame:CGRectMake(16, 65, 72, 72)];
        [minImageView sd_setImageWithURL:[NSURL URLWithString:minImageUrl] placeholderImage:[UIImage imageNamed:@"authenUploadImage"]];
        UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:minImageUrl]]];
        if (image == nil) {
            [minImageView sd_setImageWithURL:[NSURL URLWithString:largeImageUrl] placeholderImage:[UIImage imageNamed:@"authenUploadImage"]];
        }
        [cell addSubview:minImageView];
        
        UITapGestureRecognizer * tapImage = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showLargeImage)];
        minImageView.userInteractionEnabled = YES;
        [minImageView addGestureRecognizer:tapImage];
    }
    else
    {
        certificateTextField = [[UITextField alloc]initWithFrame:CGRectMake(22, 12, UI_SCREEN_WIDTH - 22, 17)];
        certificateTextField.font = [UIFont systemFontOfSize:15.0];
        certificateTextField.textColor = UIColorFromRGB(0x333333);
        certificateTextField.delegate = self;
        certificateTextField.placeholder = NSLocalizedString(@"input", @"请输入...");
        certificateTextField.text = certificateString;
        certificateTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        certificateTextField.keyboardType = UIKeyboardTypeAlphabet;
        [cell addSubview:certificateTextField];
    }
    return cell;
}

#pragma mark ---拍照
-(void)getImageFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark --从相册中获取

-(void)getImageFromPhoto
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = NO;
    [self presentViewController:pickerImage animated:YES completion:nil];
    
}

#pragma mark -- 选择照片或者照相完后触发的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
    minImageView.image = image;
    newImage = image;
//    newImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
//    newImage = [UIImage imageWithData:imageData];
    imageChangeFlag = YES;
    [self checkInChange];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -------- 有图还是没有图片
-(void)showLargeImage
{
    if (([_infoModel.image isEqualToString:@""] || _infoModel.image == nil) && newImage == nil) {
        [self getFromcamreOrPhoto];
    }
    else
    {
        [self tapImageDo];
    }
}

#pragma mark ---------- 弹出选择框（照片还是拍摄）
-(void)getFromcamreOrPhoto
{
    noImageSheetView = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消")destructiveButtonTitle:NSLocalizedString(@"takePhoto", @"拍照") otherButtonTitles:NSLocalizedString(@"getPhotoFromAlbum", @"从相册中选择") ,nil];
    [noImageSheetView showInView:self.view];
}

#pragma mark ---------- 点击图片弹出照片还是拍摄还是查看大图
-(void)tapImageDo
{
    hasImageSheetView = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel",@"取消")destructiveButtonTitle:NSLocalizedString(@"showLargeImage", @"查看大图") otherButtonTitles:NSLocalizedString(@"takePhoto", @"拍照"),NSLocalizedString(@"getPhotoFromAlbum", @"从相册中选择"),nil];
    [hasImageSheetView showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet == noImageSheetView) {
        if (buttonIndex == 0) {
            [self getImageFromCamera];
        }
        else if (buttonIndex == 1)
        {
            [self getImageFromPhoto];
        }
    }
    else
    {
        if (buttonIndex == 0) {
             ShowLargeImageController * slic = [[ShowLargeImageController alloc]init];
            // || ![_infoModel.thumbnail isEqualToString:@""]
            if (newImage != nil) {
                slic.image = minImageView.image;
            }
            else if (![_infoModel.image isEqualToString:@""] && _infoModel.image != nil)
            {
                 slic.largeImageUrl = _infoModel.image;
            }
            [self.navigationController pushViewController:slic animated:YES];
        }
        else if (buttonIndex == 1)
        {
            [self getImageFromCamera];
        }
        else if (buttonIndex == 2)
        {
            [self getImageFromPhoto];
        }
    }
   
}



-(void)postImage:(NSData *)data
{
    if ([self IsHaveNetwork]) {
        return;
    }
    if (![self checkinInput]) {
        return ;
    }
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN  forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:certificateString forKey:@"no"];
    __weak AuthenicateImageViewController * weakSelf = self;
    [self startWaiting:nil color:nil addToView:self.view];
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

    [mgr POST:POST(SAVEAUTHIMAGE) parameters:postDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (newImage != nil) {
            [formData appendPartWithFileData:data name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpg"];
        }

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self stopWaiting];
        id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (newImage != nil) {
            NSDictionary * dataDict = [obj objectForKey:@"data"];
            _infoModel.image = [dataDict objectForKey:@"image"];
            _infoModel.thumbnail = [dataDict objectForKey:@"thumbnail"];
        }
         _infoModel.no = certificateString;
         _infoModel.status = 0;
        if (weakSelf.hasImage) {
            weakSelf.hasImage(_infoModel);
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self stopWaiting];
        if ([error.userInfo objectForKey:ERRORINFO]) {
            id obj = [NSJSONSerialization JSONObjectWithData:[error.userInfo objectForKey:ERRORINFO] options:NSJSONReadingMutableContainers error:nil];
            [PromptInfoView showMessage:[obj objectForKey:@"info"] superView:self.view];
        }
    }];
}

#pragma mark --------UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    certificateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self checkInChange];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    certificateString = textField.text;
}

#pragma mark ------- 检查图片是否改变
-(void)checkInChange
{
    if (![certificateString isEqualToString:_infoModel.no] || imageChangeFlag) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    }
}

#pragma mark --------- 检查输入
-(BOOL)checkinInput
{
    if (_infoModel.authType == 1) {
        if (![validateInputValue validateString:certificateString]) {
            [PromptInfoView showMessage:NSLocalizedString(@"companyNoError", @"企业证号格式有误") superView:self.view];
            return NO;
        }
    }
    else
    {
        if (![validateInputValue validateStringLength:certificateString minLength:1 maxLength:18]) {
            [PromptInfoView showMessage:NSLocalizedString(@"certificateFormatError", @"身份证格式有误") superView:self.view];
            return NO;
        }
    }

    if (([_infoModel.image isEqualToString:@""] || _infoModel.image == nil) && newImage == nil) {
        [PromptInfoView showMessage:NSLocalizedString(@"noImage", @"请上传图片")  superView:self.view];
        return NO;
    }
    
     NSData *imageData = UIImageJPEGRepresentation(newImage, 0.0001);
    long imageSize = [imageData length] / 1024;
    if (imageSize > 3 * 1024) {
        [PromptInfoView showMessage:NSLocalizedString(@"imageThan", @"上传图片不能大于3M") superView:self.view];
        return NO;
    }
    
    return YES;
}

#pragma mark ------- 压缩图片
-(UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage * compressImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return compressImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
